// User 模块 - 演示用户状态管理

export default {
  namespaced: true,
  
  state: {
    user: null,
    isLoggedIn: false,
    token: null
  },
  
  getters: {
    // 用户名
    username: (state) => state.user?.name || '游客',
    
    // 用户邮箱
    email: (state) => state.user?.email || '',
    
    // 是否已登录
    isAuthenticated: (state) => state.isLoggedIn,
    
    // 用户信息摘要
    userSummary: (state) => {
      if (!state.user) return '未登录'
      return `${state.user.name} (${state.user.email})`
    }
  },
  
  mutations: {
    // 设置用户信息
    SET_USER(state, user) {
      state.user = user
      state.isLoggedIn = !!user
    },
    
    // 设置 token
    SET_TOKEN(state, token) {
      state.token = token
    },
    
    // 登出
    LOGOUT(state) {
      state.user = null
      state.isLoggedIn = false
      state.token = null
    },
    
    // 更新用户信息
    UPDATE_USER(state, updates) {
      if (state.user) {
        state.user = { ...state.user, ...updates }
      }
    }
  },
  
  actions: {
    // 登录
    async login({ commit }, { username, password }) {
      // 模拟 API 调用
      return new Promise((resolve) => {
        setTimeout(() => {
          const user = {
            id: 1,
            name: username,
            email: `${username}@example.com`,
            avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`
          }
          const token = 'mock_token_' + Date.now()
          
          commit('SET_USER', user)
          commit('SET_TOKEN', token)
          
          // 保存到 localStorage
          localStorage.setItem('user', JSON.stringify(user))
          localStorage.setItem('token', token)
          
          resolve(user)
        }, 500)
      })
    },
    
    // 登出
    logout({ commit }) {
      commit('LOGOUT')
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    },
    
    // 从 localStorage 恢复登录状态
    restoreLogin({ commit }) {
      const userStr = localStorage.getItem('user')
      const token = localStorage.getItem('token')
      
      if (userStr && token) {
        const user = JSON.parse(userStr)
        commit('SET_USER', user)
        commit('SET_TOKEN', token)
      }
    },
    
    // 更新用户信息
    updateProfile({ commit }, updates) {
      commit('UPDATE_USER', updates)
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const user = JSON.parse(userStr)
        const updatedUser = { ...user, ...updates }
        localStorage.setItem('user', JSON.stringify(updatedUser))
      }
    }
  }
}

